package com.ray.finance.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ray.common.check.AbstractCheck;
import com.ray.finance.builder.BillPayBuilder;
import com.ray.finance.check.BillCheck;
import com.ray.finance.enums.PayTypeEnum;
import com.ray.finance.service.FinaBillPayService;
import com.ray.finance.service.FinaBillService;
import com.ray.finance.table.dto.BillPayQueryDTO;
import com.ray.finance.table.dto.BillAmountChangeDTO;
import com.ray.finance.table.entity.FinaBill;
import com.ray.finance.table.entity.FinaBillPay;
import com.ray.finance.table.params.bill.BillPayCreateParams;
import com.ray.finance.table.params.bill.BillPayQueryParams;
import com.ray.finance.table.vo.BillPayVO;
import com.ray.system.enums.FileTypeEnum;
import com.ray.system.service.SysFileService;
import com.ray.system.table.entity.SysFile;
import com.ray.util.FileRecordUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.config.SysFileConfig;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 对账单
 * @Class: BillApi
 * @Package com.ray.finance.api
 * @date 2020/6/15 15:35
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Service
public class BillPayApi {


    @Autowired
    private FinaBillService finaBillService;
    @Autowired
    private FinaBillPayService finaBillPayService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private SysFileConfig sysFileConfig;

    /**
     *
     * @param queryParams
     * @return
     */
    public Result<List<BillPayVO>> queryPays(BillPayQueryParams queryParams) {
        Assert.notNull(queryParams, "参数[queryParams]不存在");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        BillPayQueryDTO queryDTO = new BillPayQueryDTO();
        BeanUtil.copyProperties(queryParams, queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<FinaBillPay> finaBillAdjusts = finaBillPayService.list(queryDTO, loginUser);
        //查询对象
        List<BillPayVO> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(finaBillAdjusts)) {
            list = finaBillAdjusts.stream().map(billPay -> {
                BillPayVO billPayVO = new BillPayVO();
                BeanUtil.copyProperties(billPay, billPayVO);
                //查询图片信息
                List<SysFile> files = sysFileService.queryFiles(billPay.getPayCode(),FileTypeEnum.PAY.getValue(),loginUser);
                billPayVO.setFiles(FileRecordUtil.toFileVO(files,sysFileConfig));
                return billPayVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }


    /**
     * 创建支付记录
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createPay(BillPayCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBill finaBill = finaBillService.queryBillByBillNo(createParams.getBillNo(),loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在").checkPay("对账单不能付款");
        BillPayBuilder billPayBuilder = new BillPayBuilder();
        billPayBuilder.append(createParams).appendPayType(PayTypeEnum.NORMAL.getValue()).appendCreate(loginUser);
        //保存支付记录信息
        if (!finaBillPayService.save(billPayBuilder.bulid())) {
            log.info("保存付款单接口异常,参数:{}", JSON.toJSONString(billPayBuilder.bulid()));
            throw BusinessExceptionFactory.newException("保存付款单接口异常");
        }
        BillAmountChangeDTO billAmountChangeDTO = new BillAmountChangeDTO(finaBill.getBillNo(),finaBill.getPayAmount().add(createParams.getAmount()),finaBill.getUpdateVersion());
        if(!finaBillService.updatePayAmount(billAmountChangeDTO,loginUser)){
            throw  BusinessExceptionFactory.newException("更新对账单付款金额");
        }
        //保存文件
        sysFileService.saveFile(billPayBuilder.getCode(),FileTypeEnum.PAY, FileRecordUtil.toFileDTO(createParams.getFiles()),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, billPayBuilder.getCode());
    }


    @Transactional
    public Result<String> deletePay(String payCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBillPay finaBillPay = finaBillPayService.queryPayByNo(payCode,loginUser);
        new AbstractCheck<>(finaBillPay).checkNull("付款单不存在");
        if(StrUtil.equals(finaBillPay.getPayType(),PayTypeEnum.ADVANCE.getValue())){
            throw  BusinessExceptionFactory.newException("预付款记录不能删除");
        }
        BillPayBuilder billPayBuilder = new BillPayBuilder();
        billPayBuilder.appendCode(payCode).delete().appendEdit(loginUser);
        //保存支付记录信息
        if (!finaBillPayService.edit(billPayBuilder.bulid(),loginUser)) {
            log.info("删除付款单接口异常,参数:{}", JSON.toJSONString(billPayBuilder.bulid()));
            throw BusinessExceptionFactory.newException("删除付款单接口异常");
        }
        //查询调整单
        FinaBill finaBill = finaBillService.queryBillByBillNo(finaBillPay.getBillNo(),loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在");
        BillAmountChangeDTO billAmountChangeDTO = new BillAmountChangeDTO(finaBill.getBillNo(),finaBill.getPayAmount().subtract(finaBillPay.getAmount()),finaBill.getUpdateVersion());
       if(!finaBillService.updatePayAmount(billAmountChangeDTO,loginUser)){
           throw  BusinessExceptionFactory.newException("更新付款单金额");
       }
       //删除文件
        sysFileService.deleteFile(payCode, FileTypeEnum.PAY.getValue(),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, billPayBuilder.getCode());
    }



    @Transactional
    public Result<BillPayVO> viewPay(String payCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBillPay finaBillPay = finaBillPayService.queryPayByNo(payCode,loginUser);
        new AbstractCheck<>(finaBillPay).checkNull("付款单不存在");
        BillPayVO billPayVO = new BillPayVO();
        BeanUtil.copyProperties(finaBillPay, billPayVO);
        //查询图片信息
        List<SysFile> files = sysFileService.queryFiles(payCode,FileTypeEnum.PAY.getValue(),loginUser);
        billPayVO.setFiles(FileRecordUtil.toFileVO(files,sysFileConfig));
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, billPayVO);
    }

}
